import re
from  urllib import  request
class Spider():
    url = 'https://www.panda.tv/cate/lol'
    #[\s\S]匹配任意字符
    # [\s\S]*匹配任意多字符
    # ？改贪婪模式为非贪婪模式（因为由于有许多</div>）改为匹配第一个
    #加上括号变成组 结果只有（）中的内容
    root_pattern = '<div class="video-info">([\s\S]*?)</div>'
    name_pattern = '</i>([\s\S]*?)</span>'
    number_pattern = '<span class="video-number">([\s\S]*?)</span>'
   #获取字符串页面代码
    def __fetch_content(self):
        r = request.urlopen(Spider.url)
        htmls = r.read()
        htmls = str(htmls,encoding='UTF-8')
        return  htmls
    #代码分装
    def __analusis(self,htmls):
       root_html =  re.findall(Spider.root_pattern,htmls)
       anchors = []
       for html in  root_html:
           name = re.findall(Spider.name_pattern,html)
           number = re.findall(Spider.number_pattern,html)
           anchor = {'name':name,'number':number}
           anchors.append(anchor)
       #print(anchors[0])
       return anchors
    #数据排版
    def __refine(self,anchors):
        #strip()  去掉空白
        l = lambda anchor:{'name':anchor['name'][0].strip(),'number':anchor['number'][0].strip()}
        return  map(l,anchors)
    #排序
    def __sort(self,anchors):
        #key 指定那个元素为排序key   ,reverse=True  改升序为降序
        anchors = sorted(anchors,key=self.__sort_seed,reverse=True)
        return anchors
    #排序key
    def __sort_seed(self,anchor):
        #保留数字部分
        r = re.findall('\d*',anchor['number'])
        #类型转换
        number = float(r[0])
        if '万' in anchor['number']:
            number *= 10000
        return number
    #输出
    def __show(self,anchors):
        for rank in range(0,len(anchors)):
            #print(anchor['name']+'----------'+anchor['number'])
            print(str(rank+1)+':'+anchors[rank]['name']+'    '+anchors[rank]['number'])
    def go(self):
        htmls = self.__fetch_content()
        anchors = self.__analusis(htmls)
        anchors = list(self.__refine(anchors))
        anchors = self.__sort(anchors)
        self.__show(anchors)

spilder = Spider()
spilder.go()